<script setup>
import { ref } from 'vue'
import { useVModel } from '@vueuse/core'
import { useUpload } from '@/hooks/upload'

const props = defineProps({
  modelValue: Boolean,
  detail: Object
})
const emits = defineEmits(['submit', 'update:modelValue'])
const dialogVisible = useVModel(props, 'modelValue', emits)

const ruleForm = ref({
  materialName: '',
  materialUrl: ''
})
const rules = {
  materialName: {
    required: true,
    message: '请输入素材名称',
    trigger: 'change'
  },
  materialUrl: {
    required: true,
    message: '请上传素材',
    trigger: 'change'
  }
}

const { select } = useUpload({
  size: 2,
  onChange(url) {
    ruleForm.value.materialUrl = url
  }
})

const ruleFormRef = ref()
const handleSubmit = async () => {
  await ruleFormRef.value.validate()
  emits('submit', ruleForm.value)
}

const handleClose = done => done()

const handleOpen = () => {
  ruleFormRef.value.resetFields()

  if (props.detail) {
    Object.assign(ruleForm.value, props.detail)
  }
}
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    width="768px"
    :before-close="handleClose"
    :close-on-click-modal="false"
    v-bind="$attrs"
    @open="handleOpen"
  >
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="100px"
      label-position="right"
      label-suffix="："
    >
      <el-form-item label="素材名称" prop="materialName">
        <el-input v-model.trim="ruleForm.materialName" clearable />
      </el-form-item>
      <el-form-item label="上传素材" prop="materialUrl">
        <el-input v-model.trim="ruleForm.materialUrl" clearable>
          <template #suffix>
            <el-button link type="primary" @click="select"> 上传 </el-button>
          </template>
        </el-input>

        <div class="px-4">
          <h5>tips:</h5>
          <p class="ms-2 mt-1 text-xs">
            1. 点击输入框右方按钮上传(或 输入图片的远程地址)
          </p>
          <p class="ms-2 mt-1 text-xs">2. 建议图片大小不超过2MB</p>
        </div>

        <el-image
          v-if="ruleForm.materialUrl"
          class="mt-2 h-24 w-24 overflow-hidden rounded [&:hover>img]:scale-125 [&>img]:transition-transform [&>img]:duration-300"
          :src="ruleForm.materialUrl"
          :preview-src-list="[ruleForm.materialUrl]"
          :zoom-rate="1.2"
          :max-scale="7"
          :min-scale="0.2"
          preview-teleported
          hide-on-click-modal
          fit="cover"
          lazy
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false"> 取消 </el-button>
      <el-button type="primary" @click="handleSubmit"> 确认 </el-button>
    </template>
  </el-dialog>
</template>
